use rocket::serde::json::Json;
use serde::{Deserialize, Serialize};
use super::manager::{SERVICE_MANAGER, service_struct_from_client, refresh_service_from_client};
use super::service::{Service, ServiceStructA};
use rocket::response::status::Accepted;
use std::sync::Arc;
use tokio::sync::Mutex;
use crate::protocol::service::{Addr, ServiceId};
use crate::protocol::task::SymbolicTask;
use std::collections::HashMap;
use crate::tasks::routes::create_task_func;
use crate::error::ServerError;

macro_rules! mgr_init_err {
    () => {
        ServerError::ServiceErrorStr("服务管理器未初始化")
    };
}

macro_rules! get_manager {
    () => {
        SERVICE_MANAGER.get().ok_or_else(|| mgr_init_err!())
    };
}


#[get("/services/get")]
pub async fn list_services() -> Result<Json<HashMap<Addr, Service>>, ServerError> {
    let manager = get_manager!()?.lock().await;
    Ok(Json(manager.get_services().clone()))
}

#[post("/services/add", data = "<service>")]
pub async fn add_service(service: Json<ServiceStructA>) -> Result<(), ServerError> {
    service_struct_from_client(service.into_inner()).await
}

#[delete("/services/delete/<id>")]
pub async fn delete_service(id: &str) -> Result<(), ServerError> {
    let mut manager = get_manager!()?.lock().await;
    manager.remove_service(id.to_string());
    Ok(())
}

#[get("/services/get/<id>")]
pub async fn get_service(id: &str) -> Result<Json<Service>, ServerError> {
    let manager = get_manager!()?.lock().await;
    match manager.get_service(&id.to_string()) {
        Some(service) => Ok(Json(service.clone())),
        None => Err(ServerError::ServiceErrorStr("服务ID不存在"))
    }
}

#[get("/services/refresh/<id>")]
pub async fn refresh_service(id: &str) -> Result<(), ServerError> {
    refresh_service_from_client(id.to_string()).await
}

#[derive(Debug, Clone, Deserialize)]
pub struct StartTaskA {
    service_id: ServiceId,
    task_name: String,
    input_file_content: String
}

#[post("/services/start_task", data = "<recv>")]
pub async fn service_start_task(recv: Json<StartTaskA>) -> Result<(), ServerError> {
    let json_data = recv.into_inner();
    let manager = get_manager!()?.lock().await;
    if let Some(mut service) = manager.get_service(&json_data.service_id) {
        drop(manager);
        service.mount().await?;
        let mut manager = get_manager!()?.lock().await;
        manager.renew_service(&service);
        drop(manager);
        if let Some(task) = service.get_task(&json_data.task_name) {
            let res = create_task_func(&service, task, json_data.input_file_content).await;
            return res;
        } else {
            Err(ServerError::ServiceErrorStr("任务不存在"))
        }
    } else {
        Err(ServerError::ServiceErrorStr("服务ID不存在"))
    }
}
